﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MvvmTreeView;
using System.Linq;
using System.Windows.Controls.Primitives;

namespace System.Windows.Controls
{
    public static class Extensions
    {
        public static TreeViewItem HitTest(this TreeView treeView, MouseEventArgs e)
        {
            var list = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), treeView as UIElement);
            var item = list.FirstOrDefault(u => u.IsChildOfTreeViewItem());
            var treeViewItem = (TreeViewItem)null;

            if (item != null)
            {
                treeViewItem = item.GetParentTreeViewItem();
            }

            return treeViewItem;
        }

        public static TreeViewItem HitTest(this WindowsStyleTreeViewDragDropTarget dragDropTarget, MouseEventArgs e)
        {
            var list = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), dragDropTarget as UIElement);
            var item = list.FirstOrDefault(u => u.IsChildOfTreeViewItem());
            var treeViewItem = (TreeViewItem)null;

            if (item != null)
            {
                treeViewItem = item.GetParentTreeViewItem();
            }

            return treeViewItem;
        }

        public static bool IsChildOfTreeViewItem(this UIElement element)
        {
            var isChild = element.GetVisualAncestorsAndSelf().Any(d => d is TreeViewItem);

            return isChild;
        }

        public static TreeViewItem GetParentTreeViewItem(this UIElement element)
        {
            var treeViewItem = element.GetVisualAncestorsAndSelf().OfType<TreeViewItem>().FirstOrDefault();

            return treeViewItem;
        }

        private static TreeNodeItemContent FindContent(FrameworkElement obj)
        {
            TreeNodeItemContent result = null;

            if (obj != null)
            {
                result = obj as TreeNodeItemContent;

                if (result == null)
                {
                    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
                    {
                        var child = VisualTreeHelper.GetChild(obj, i) as FrameworkElement;

                        result = FindContent(child);

                        if (result != null)
                        {
                            break;
                        }
                    }
                }
            }

            return result;
        }

        public static TreeNodeItemContent GetContent(this TreeViewItem item)
        {
            TreeNodeItemContent content = FindContent(item);

            return content;
        }
    }
}
